//
//  NSURL+Backup.m
//  Leaflet
//
//  Created by l.t.zero on 2018/8/16.
//  Copyright © 2018 Starunion. All rights reserved.
//

#import "NSURL+Backup.h"
#include <sys/xattr.h>

@implementation NSURL(Backup)

+ (void)excludedFromBackupKey{
    //如果要指定其他文件目录，比如Caches目录，需要更换目录工厂常量，上面代码其他的可不变
    NSArray *pathcaches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory
                                                              , NSUserDomainMask
                                                              , YES);
    
    for (NSString *path in pathcaches){
        [self addSkipBackupAttributeToItemAtURL: [NSURL fileURLWithPath:path]];
    }
    
    //如果要指定其他文件目录，比如Caches目录，需要更换目录工厂常量，上面代码其他的可不变
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory
                                                             , NSUserDomainMask
                                                             , YES);
    
    for (NSString *path in documents){
        [self addSkipBackupAttributeToItemAtURL: [NSURL fileURLWithPath:path]];
    }
}
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    const char* filePath = [[URL path] fileSystemRepresentation];
    
    extern NSString * const NSURLIsExcludedFromBackupKey __attribute__((weak_import));
    
    const char* attrName = "com.apple.MobileBackup";
    
    int result = (int)getxattr(filePath, attrName, NULL, sizeof(u_int8_t), 0, 0);
    BOOL bAttr501Existed = (result != -1);
    
    if (&NSURLIsExcludedFromBackupKey == nil) {
        if (bAttr501Existed) {
            return YES;
        }
        
        // The attribute exists, we need to remove it
        u_int8_t attrValue = 1;
        int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
        return result == 0;
        
    }
    else {
        // First try and remove the extended attribute if it is present
        if (bAttr501Existed) {
            // The attribute exists, we need to remove it
            int removeResult = removexattr(filePath, attrName, 0);
            if (removeResult == 0) {
                NSLog(@"Removed extended attribute on file %@", URL);
            }
        }
        
        NSNumber*  bKey51MoreExisted = nil;
        if ([URL getResourceValue:&bKey51MoreExisted forKey:NSURLIsExcludedFromBackupKey error:nil]) {
            if ([bKey51MoreExisted boolValue]){
                return YES;
            }
        }
        
        // Set the new key
        NSError *error = nil;
        [URL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&error];
        return error == nil;
    }
    return YES;
}

@end
